package com.muzuo.pdf.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.MathTool;
import org.apache.velocity.tools.generic.NumberTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.pdf.BaseFont;
import com.muzuo.pdf.entity.User;
import com.muzuo.pdf.service.IPdfService;
import com.muzuo.pdf.util.DictionaryUtil;

@Service
public class PdfServiceImpl implements IPdfService{
    
    @Value("${pdf.PDFtemplatePath}")
    private String PDFtemplatePath;
    @Value("${pdf.pdfFilePath}")
    private String pdfFilePath;
    
    @Override
    public boolean createPdf(User user) {
        try {
            Properties properties = new Properties();
            // 设置velocity的模版路径
            properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, PDFtemplatePath);
            // 设置编码
            properties.setProperty(VelocityEngine.INPUT_ENCODING, "UTF-8");
            properties.setProperty(VelocityEngine.OUTPUT_ENCODING, "UTF-8");
            VelocityEngine ve = new VelocityEngine();
            ve.init(properties);
            // 获取PDF模板 可以有自己的规则 用于取不同的模板
            Template t = ve.getTemplate("template.vm", "UTF-8");
            // 取得velocity的上下文context
            VelocityContext context = new VelocityContext();
            // 给context添加方法 用于页面调用
            getContext(context);
            // 将数据添加到模板中 建议使用map 这样可以兼容多个模块
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("name", user.getName());
            dataMap.put("sex", user.getSex());
            dataMap.put("mobile", user.getMobile());
            dataMap.put("address", user.getAddress());
            dataMap.put("registerTime", user.getRegisterTime());
            
            context.put("dataMap", dataMap);
            // 输出流
            StringWriter writer = new StringWriter();
            t.merge(context, writer);

            java.io.File filePath = new java.io.File(pdfFilePath);
            if (!filePath.exists()) {
                filePath.mkdir();
            }
            String fileName = user.getName() + UUID.randomUUID().toString() + ".pdf";
            String outputFile = filePath +File.separator+ fileName;
            OutputStream os = new FileOutputStream(outputFile);
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(PDFtemplatePath + "/font/simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.setDocumentFromString(writer.toString());
            renderer.layout();
            renderer.createPDF(os);
            os.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    private void getContext(VelocityContext context) {
        context.put("number", new NumberTool());
        context.put("math", new MathTool());
        context.put("date", new DateTool());
        //自定义方法 可扩展
        context.put("dictionaryUtil", new DictionaryUtil());
    }

}
